package com.smw.controller;

import com.smw.pojo.User;
import com.smw.send.SendEmail;
import com.smw.service.CodeService;
import com.smw.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private CodeService codeService;
    //登录
    @RequestMapping("/login")
    public String login (User user, Model model){
        System.out.println(user);
        try {
            //System.out.println("第一步");
            Subject subject = SecurityUtils.getSubject();
            //System.out.println("第二步");
            AuthenticationToken token = new UsernamePasswordToken(user.getUserName(), user.getPassWord());
            //System.out.println(token+"第三步");
            subject.login(token);
            subject.hasRole("106");
            return "index";
        }catch (Exception e){
            e.printStackTrace();
            return "loginError";
        }
    }
    //获取验证码
    @RequestMapping("/getCode")
    @ResponseBody
    public String login (String userName,HttpServletRequest request){
        //System.out.println(userName);
        String email=userService.findEmailByUserName(userName);
       // System.out.println(email);
        if (email==null){
            return "0";
        }else{
            StringBuffer sbCode = new StringBuffer();
            System.out.println("进入邮箱验证登录");
            Random r = new Random();
            for (int i = 0; i < 6; i++) {
                int txt = r.nextInt(10);
                String str = String.valueOf(txt);
                sbCode.append(str);
            }
            //将验证码存到session中，方便登录时来获取这个验证去校验用户登陆时所输入的验证码是否正确
            request.getSession().setAttribute("code", sbCode.toString());
            //拼接邮件内容
            String code=sbCode.toString();
            String msg = "验证码：" + sbCode.toString() + ",30分钟内有效";
            //System.out.println("验证码为"+msg);
            codeService.saveCode(email,code);
            boolean flag= SendEmail.sendMail(email, msg);
            if(flag){
                return "1";
            }else{
                return "0";
            }
        }


    }
    @RequestMapping("/login2")
    @ResponseBody
    public String login2(User user){

        String email=userService.findEmailByUserName(user.getUserName());
        if (user.getEmailCode().equals(codeService.findCodeByKey(email))){
            return "1";

        }else{
            return "0";
        }

    }
    @RequestMapping("/getEmailCode")
    @ResponseBody
    public String getEmailCode(String email, HttpServletRequest request) {

        StringBuffer sbCode = new StringBuffer();
        System.out.println("进入邮箱验证码");
        Random r = new Random();
        for (int i = 0; i < 6; i++) {
            int txt = r.nextInt(10);
            String str = String.valueOf(txt);
            sbCode.append(str);
        }
        //将验证码存到session中，方便登录时来获取这个验证去校验用户登陆时所输入的验证码是否正确
        request.getSession().setAttribute("code", sbCode.toString());
        //拼接邮件内容
        String code=sbCode.toString();
        String msg = "验证码：" + sbCode.toString() + ",30分钟内有效";
        //System.out.println("验证码为"+msg);
        codeService.saveCode(email,code);
        boolean flag= SendEmail.sendMail(email, msg);
        if(flag){
            return "1";
        }else{
            return "0";
        }

    }
    //检查重名
    @RequestMapping("/checkName")
    @ResponseBody
    public String checkName(String userName){
        String u = userService.findUserNameByName(userName);
        System.out.println("查询的名字为："+userName);
            if (u == null) {
                return "1";
            } else {
                return "0";
            }
    }
//    @RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
//    @ResponseBody
//    public Map upLoadImg(HttpServletRequest request, String userImg, @RequestParam("file") CommonsMultipartFile file) {
//        System.out.println("开始：" + userImg);
//        Map res = new HashMap();
//        InputStream is = null;
//        OutputStream os = null;
//        OutputStream oos = null;
//        String newImg = System.currentTimeMillis() + file.getOriginalFilename();
//        String path = request.getSession().getServletContext().getRealPath("");
//        try {
//            is = file.getInputStream();
//            os = new FileOutputStream(new File("D:\\idea\\end\\theend\\src\\main\\resources\\static\\img\\" + newImg));
//            oos = new FileOutputStream(new File(path + "\\" + newImg));
//            int i;
//
//            while ((i = is.read()) != -1) {
//                os.write(i);
//                oos.write(i);
//            }
//
//            os.flush();
//            oos.flush();
//
//            //user.setUserImg(newImg);
//
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                os.close();
//                oos.close();
//                is.close();
//
//            } catch (Exception e) {
//                // TODO: handle exception
//                e.printStackTrace();
//            }
//        }
//
//        System.out.println("最后：" + userImg);
//        res.put("code", "0");
//        res.put("data", newImg);
//        return res;
//    }
    @ResponseBody
    @RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
    public Map<String, Object> uploadFile(HttpServletRequest request, String userImg, @RequestParam("file") MultipartFile file)
    {

        System.out.println("进入上传文件");
        System.out.println("开始：" + userImg);
        Map res = new HashMap();
        InputStream is = null;
        OutputStream os = null;
        OutputStream oos = null;
        String newImg = System.currentTimeMillis() + file.getOriginalFilename();
        String path = request.getSession().getServletContext().getRealPath("");
        try {
            is = file.getInputStream();
            os = new FileOutputStream(new File("D:\\idea\\end\\theend\\src\\main\\resources\\static\\img\\" + newImg));
            oos = new FileOutputStream(new File(path + "\\" + newImg));
            int i;

            while ((i = is.read()) != -1) {
                os.write(i);
                oos.write(i);
            }

            os.flush();
            oos.flush();

            //user.setUserImg(newImg);


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
                oos.close();
                is.close();

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }

        System.out.println("最后：" + userImg);
        res.put("code", "0");
        res.put("data", newImg);
        return res;
    }

    //去注册页面
    @RequestMapping("toReg")
    public String toReg(){
        return "reg";
    }
    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }
    @RequestMapping("toLogin2")
    public String toLogin2(){
        return "login2";
    }
    @RequestMapping("toIndex")
    public String toIndex(){
        return "index";
    }


}
